package com.base.common.utils;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VerifyUtils {

    public static boolean checkPhoneNumber(String phone) {
        phone = phone.replaceAll(" ", "");
        Pattern p = Pattern.compile("^[1][3-9][0-9]{9}$"); // 验证手机号
        Matcher m = p.matcher(phone);
        return m.matches();
    }

    public static void onTextChangedPhone(EditText editText) {
        if (editText == null) return;
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0)
                    return;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < s.length(); i++) {
                    if (i != 3 && i != 8 && s.charAt(i) == ' ') {
                        continue;
                    } else {
                        sb.append(s.charAt(i));
                        if ((sb.length() == 4 || sb.length() == 9)
                                && sb.charAt(sb.length() - 1) != ' ') {
                            sb.insert(sb.length() - 1, ' ');
                        }
                    }
                }
                if (!sb.toString().equals(s.toString())) {
                    int index = start + 1;
                    int in = sb.length();
                    if (in > start) {
                        if (sb.charAt(start) == ' ') {
                            if (before == 0) {
                                index++;
                            } else {
                                index--;
                            }
                        } else {
                            if (before == 1) {
                                index--;
                            }
                        }
                    }
                    if (index > in) index = in;
                    editText.setText(sb.toString());
                    editText.setSelection(index);

                }



                //删除
                if (count == 0 && before > 0) {
                    LogUtil.d(start + "  " + count + " ");
                }

                //添加
                if (before == 0 && count > 0) {
                    LogUtil.d(count + " " + before);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

}
